import DetailsSubmit from '@/pages/cues/topic/submit/components/DetailsSubmit';
import { pageCuesSeekSubmit } from '@/services/api/api-cues-seek';
import { searchTreeOrganization, submitAnalysis } from '@/services/api/api-cues-submit';
import { FileImageOutlined, PaperClipOutlined } from '@ant-design/icons';
import { LightFilter, ProFormCascader, ProFormDateRangePicker } from '@ant-design/pro-components';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { Cascader, Input, Space, Tag } from 'antd';
import { DefaultOptionType } from 'antd/lib/select';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
interface TableTopicSubmitProps {
  isEditable: boolean;
}

const TableSubmit: React.FC<TableTopicSubmitProps> = (props) => {
  const { isEditable } = props;
  const access = useAccess();
  const [loading, setLoadingState] = useState(true);
  const [responsive, setResponsive] = useState(false);
  const [totalData, setTotalDataState] = useState<CuesSubmitData.Analysis>();
  const [width, setWidth] = useState(500);

  const actionRef = useRef<ActionType>();

  const [articleOrganizations, setArticleOrganizationState] = useState<any[]>([]);

  /**
   * 加载 单位 列表
   * @param key
   */
  const analysisData = async () => {
    try {
      const response = await submitAnalysis();
      if (response.code === 0) {
        console.log(response.data);
        setLoadingState(false);
        setTotalDataState(response.data);
      }
    } catch (error) {}
  };
  /**
   * 加载 单位 列表
   * @param key
   */
  const treeOrganizationData = async () => {
    try {
      const response = await searchTreeOrganization();
      if (response.code === 0) {
        setArticleOrganizationState(response.data);
      }
    } catch (error) {}
  };

  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({});

  useEffect(() => {
    treeOrganizationData();
    analysisData();
  }, []);

  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return (
    <ProTable<CuesSubmitData.SubmitPage>
      columns={[
        {
          title: '报送线索',
          dataIndex: 'articleName',
          // copyable: true,
          search: false,
          ellipsis: true,
          width: '250px',
          align: 'center',
          key: 'articleName',
          render: (dom, record, _index, action) => {
            return (
              <div
                style={{
                  textAlign: 'left',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {record.isImage === 1 ? <FileImageOutlined /> : <></>}
                {record.isFile === 1 ? <PaperClipOutlined /> : <></>}
                <DetailsSubmit
                  id={record.id}
                  name={record.articleName}
                  onRefurbish={() => {
                    actionRef.current?.reload();
                  }}
                />
              </div>
            );
          },
        },
        {
          title: '选题计划',
          dataIndex: 'topicName',
          // copyable: true,
          ellipsis: true,
          search: false,
          width: '150px',
          align: 'center',
          key: 'topicName',
        },
        {
          title: '选题方向',
          dataIndex: 'articleIndustryName',
          key: 'articleIndustryName',
          width: '100px',
          align: 'center',
          search: false,
          render: (_, row) => {
            let industrys = row?.articleIndustrys;

            if (industrys.length > 2) {
              industrys = industrys.slice(0, 2);
              industrys.push({
                label: '...',
                value: '...',
              });
            }

            return (
              <Space size={[0, 8]} wrap>
                {industrys?.map(
                  (item) => (
                    <Tag key={item.value}>{item.label}</Tag>
                  ),
                  // <div >{item.label}</div>,
                )}
              </Space>
            );
          },
        },
        {
          title: '单位',
          key: 'articleOrganizationAvatar',
          dataIndex: 'articleOrganizationAvatar',
          width: '150px',
          search: false,
          align: 'center',
          valueType: 'avatar',
          render: (dom, row) => (
            <div
              style={{
                textAlign: 'left',
                marginLeft: '16px',
              }}
            >
              {/* <Tag color={findTagColor(row.articleOrganizationTopName)}>
              {row.articleOrganizationTopName}
            </Tag> */}
              <span>{dom}</span>
              {row.articleOrganizationName}
            </div>
          ),
        },
        {
          title: '新闻联络人',
          dataIndex: 'articleAccountName',
          // copyable: true,
          ellipsis: true,
          search: false,
          width: '100px',
          align: 'center',
          key: 'articleAccountName',
        },

        // {
        //   title: '阅读情况',
        //   hideInSearch: true,
        //   hideInTable: !access.线索征集x配置x管理员,
        //   dataIndex: 'receipt',
        //   key: 'receipt',
        //   valueType: 'avatar',
        //   width: '80px',
        //   align: 'center',
        //   search: false,
        //   render: (dom, record) => {
        //     return <ReceiptSubmit id={record.id} receipt={'123'} />;
        //   },
        // },
        {
          title: '浏览次数',
          hideInSearch: true,
          hideInTable: !access.线索征集x配置x管理员,
          dataIndex: 'receipt',
          key: 'receipt',
          valueType: 'avatar',
          width: '80px',
          align: 'center',
          search: false,
          render: (dom, record) => {
            return <a>{record.readCount}</a>;
          },
        },
        {
          title: '创建时间',
          dataIndex: 'createdTime',
          key: 'createdTime',
          width: '120px',
          align: 'center',
          search: false,
        },
      ]}
      actionRef={actionRef}
      request={async (params = {}) => {
        // if (params.organizationIds) {
        //   const organizationParentIds: string[] = [];
        //   let organizationIds: string[] = [];

        //   params.organizationIds.forEach((item: string | any[]) => {
        //     if (item.length === 1) {
        //       organizationParentIds.push(item[0]);
        //     } else if (item.length > 1) {
        //       organizationIds.push(item[1]);
        //     }
        //   });
        //   organizationParentIds.forEach((id) => {
        //     const ids = articleOrganizations.find((item) => item.id === id).children;
        //     organizationIds = organizationIds.concat(ids.map((item: any) => item.id));
        //   });
        //   params.articleOrganizationIds = organizationIds;
        // }

        const response = await pageCuesSeekSubmit({
          mode: 1,
          createdSource: 1,
          ...queryParam,
          ...params,
        });

        return Promise.resolve({
          data: response.data.data,
          total: response.data.total,
          success: response.code === 0,
        });
      }}
      rowKey="id"
      dateFormatter="string"
      bordered
      search={false}
      sticky
      ghost
      pagination={{
        showQuickJumper: true,
        showSizeChanger: true,
        defaultPageSize: 20,
      }}
      headerTitle={
        <div
          style={{
            display: 'flex',
          }}
        >
          <Input.Search
            placeholder="查询标题"
            enterButton="搜索"
            allowClear
            style={{ maxWidth: 522, width: '100%' }}
            onChange={(e) => {
              setQueryParamState({ ...queryParam, articleName: e.target.value });
            }}
            onSearch={(value) => {
              actionRef.current?.reset();
            }}
          />

          {/* <ProFormCascader
            width="xl"
            name="articleOrganizationIds"
            placeholder="选择单位"
            formItemProps={{
              style: {
                width: width - 700,
                marginLeft: '18px',
                marginBottom: '0px',
              },
            }}
            fieldProps={{
              options: articleOrganizations,
              showSearch: { filter },
              multiple: true,
              removeIcon: true,
              allowClear: true,
              maxTagCount: 'responsive',
              showCheckedStrategy: Cascader.SHOW_CHILD,
              onChange(value, selectOptions) {
                setQueryParamState({ ...queryParam, articleOrganizationIds: value });
                actionRef.current?.reset();
              },
            }}
          /> */}
        </div>
      }
      toolbar={{
        style: {
          marginTop: '-16px',
        },
        filter: (
          <LightFilter
            onValuesChange={(value) => {
              setQueryParamState(value);
              actionRef.current?.reset();
            }}
          >
            <ProFormDateRangePicker
              name="createdTimes"
              label="创建日期"
              allowClear
              fieldProps={{
                allowClear: true,
                placeholder: ['开始日期', '结束日期'],
                format: 'YYYY-MM-DD',
                ranges: {
                  今日: [dayjs(), dayjs()],
                  本月: [dayjs().startOf('month'), dayjs().endOf('month')],
                  上月: [
                    dayjs().startOf('month').subtract(1, 'months'),
                    dayjs().endOf('month').subtract(1, 'months'),
                  ],
                  最近7天: [dayjs().subtract(6, 'days'), dayjs()],
                  最近60天: [dayjs().subtract(59, 'days'), dayjs()],
                  最近90天: [dayjs().subtract(89, 'days'), dayjs()],
                },
              }}
            />
          </LightFilter>
        ),
      }}
    />
  );
};

export default TableSubmit;
